﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace WROA.ActionFilter
{
    /// <summary>
    /// 每一次Action都会角色验证
    /// </summary>
    public class RoleAuthorize : ActionFilterAttribute
    {
        /// <summary>
        /// Action在执行时运行
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //读取用户cookit
            HttpCookie authCookie = filterContext.HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
            //判断是否登录超时
            if (authCookie == null || authCookie.Value == "")
            {
                filterContext.HttpContext.Response.Write("<script>alert('登录超时，请重新登录！');window.open('/Account/Login','_parent')</script>");
                return;
            }
            FormsAuthenticationTicket authTicket = null;
            try
            {
                authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            }
            catch
            {
                filterContext.HttpContext.Response.Write("<script>alert('操作错误,请重新操作！');");
                return;
            }
            string[] roles = authTicket.UserData.Split(new char[] { ';' });
            if (filterContext.HttpContext.User != null)
            {
                filterContext.HttpContext.User = new System.Security.Principal.GenericPrincipal(filterContext.HttpContext.User.Identity, roles);
            }
            string rName = (roles[0].ToString() ?? "").ToString();//读取权限
            var rolCollection = RoleName.Where(x => x == rName);
            //如果用户不在权限的范围内，就提示并导航到登陆页面
            if (rolCollection.Count() <= 0)
            {
                filterContext.HttpContext.Response.Write("<script>alert('对不起,您没有访问这个页面的权限..');window.open('/Account/Login','_parent')</script>");
                return;
            }
        }
        /// <summary>
        /// 允许访问的角色集合
        /// </summary>
        public string[] RoleName
        {
            get;
            set;
        }
    }
}